package com.eeplat.social.openapi.t360;

import java.util.Map;

import com.eeplat.social.openapi.callback.GlobalConfig;
import com.eeplat.social.openapi.http.HttpClient;
import com.eeplat.social.openapi.http.OpenApiException;
import com.eeplat.social.openapi.http.Response;
import com.eeplat.social.openapi.http.BaseAuth;

public class Auth360 extends BaseAuth{
	
	public static final String BASE = "https://openapi.360.cn/user/";

	public static final String AUTH = "https://openapi.360.cn/oauth2/authorize";

	public static final String TOKEN = "https://openapi.360.cn/oauth2/access_token";

	public static final String GET_USER_INFO = "https://openapi.360.cn/user/";
	
	/* (non-Javadoc)
	 * @see com.eeplat.social.openapi.qq.BaseURIUtil#wrappAuthCodeUri(java.lang.String)
	 */

	public String wrappAccessTokenUri(String authCode) {

		StringBuffer sb = new StringBuffer(TOKEN);
		sb.append("?grant_type=authorization_code&client_id=")
				.append(GlobalConfig.getValue("360.appkey"))
				.append("&client_secret=")
				.append(GlobalConfig.getValue("360.secret")).append("&code=")
				.append(authCode).append("&state=").append("360")
				.append("&redirect_uri=")
				.append(GlobalConfig.getValue("360.cb"));
		return sb.toString();
	}

	/* (non-Javadoc)
	 * @see com.eeplat.social.openapi.qq.BaseURIUtil#wrappAccessTokenUri(java.lang.String)
	 */

	public String wrappUserIdUri(String accessToken) {

		StringBuffer sb = new StringBuffer(BASE);
		sb.append("me.json?access_token=").append(accessToken);
		return sb.toString();
	}

	public String getAccessToken(String oauthCode) throws OpenApiException {

		String authUri = wrappAccessTokenUri(oauthCode);

		HttpClient http = new HttpClient();
		Response res;
		try {
			res = http.httpRequest(authUri,null,"GET");
			String ret = res.asString();
			Map<String, Object> data = objectMapper.readValue(ret, Map.class);
			return (String) data.get("access_token");			
		} catch (Exception e) {
			throw new OpenApiException(e);
		} 
	}

	/**
	 * 使用Access Token来获取用户的UserID
	 * 
	 * @param accessToken
	 * @return
	 * @throws OpenApiException
	 */
	public String getUserID(String accessToken) throws OpenApiException {
		String getOpenIdUri = wrappUserIdUri(accessToken);
		HttpClient http = new HttpClient();

		Map<String, Object> data;
		try {
			Response res = http.httpRequest(getOpenIdUri,null,"GET");
			String ret = res.asString();
			// callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
			data = objectMapper.readValue(ret, Map.class);
			return (String) data.get("id");
		} catch (Exception e) {
			throw new OpenApiException(e);
		}
	}
}
